package mblog.web.taobao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkDgItemCouponGetRequest;
import com.taobao.api.request.TbkTpwdCreateRequest;
import com.taobao.api.response.TbkDgItemCouponGetResponse;
import com.taobao.api.response.TbkTpwdCreateResponse;
import mblog.core.persist.service.GoodsKeywordService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

public class TaoBaoServiceImpl implements TaoBaoService {

    private RestTemplate restTemplate = new RestTemplate();
    @Autowired
    private GoodsKeywordService goodsKeywordService;

    public TbkDgItemCouponGetResponse findItemsFromTaobao(String keyword, Long size, Long pn) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(Constants.TAOBAO_API, Constants.TAOBAO_APP_KEY, Constants.TAOBAO_SECRET);
        TbkDgItemCouponGetRequest req = new TbkDgItemCouponGetRequest();
        req.setAdzoneId(Constants.TAOBAO_ADZONEID);
        req.setPageSize(size);
        req.setQ(keyword);
        req.setPageNo(pn);
        return client.execute(req);
    }


    public TbkTpwdCreateResponse createTaoKouLing(String text, String url, String logo) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(Constants.TAOBAO_API, Constants.TAOBAO_APP_KEY, Constants.TAOBAO_SECRET);
        TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
        req.setText(text);
        req.setUrl(url);
        req.setLogo(logo);
        return client.execute(req);
    }

    @Cacheable(value = "GoodsDetail", key = "#id")
    public GoodsDetail getGoodsDetail(String id) throws IOException, ApiException {
        String url = "http://170quan.cc/index.php?r=p/d&id=" + id;
        Document document = Jsoup.connect(url)
                .userAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1")
                .referrer("http://170quan.cc/index.php?r=index/wap")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                .header("Accept-Encoding", "gzip, deflate")
                .header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4")
                .header("Host", "170quan.cc")
                .header("Upgrade-Insecure-Requests", "1")
                .get();

        Elements detailWrapper = document.getElementsByClass("detail-wrapper");
        String name = detailWrapper.select("div.title-wrapper").text();
        String image = detailWrapper.select("img[data-gid]").attr("src");
        String price = detailWrapper.select("div.goods-price > b").text();
        String coupon = detailWrapper.select("div.goods-quan > b").text();
        String couponUrl = detailWrapper.select("a.tb_app").attr("href");
        String kouLing = createTaoKouLing(name, couponUrl, image).getData().getModel();
        String editorHead = detailWrapper.select("div.editor-head > img").attr("src");
        String editorTxt = detailWrapper.select("p.editor_main").text();
        String editorTime = detailWrapper.select("div.editor-time").text();
        List<String> tags = Arrays.asList(detailWrapper.select("div.goods-tag > span").text().split(" "));
        String goodsid = document.select("div.pic-detail-btn").attr("data-goodsid");
        String soldNum = document.select("div.goods-num > b").text();

        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setName(name);
        goodsDetail.setImage(image);
        goodsDetail.setPrice(price);
        goodsDetail.setCoupon(coupon);
        goodsDetail.setCouponUrl(couponUrl);
        goodsDetail.setKouLing(kouLing);
        goodsDetail.setEditorHead(editorHead);
        goodsDetail.setEditorTxt(editorTxt);
        goodsDetail.setEditorTime(editorTime);
        goodsDetail.setTags(tags);
        goodsDetail.setGoodsid(goodsid);
        goodsDetail.setSoldNum(soldNum);

        List<String> imgs = new ArrayList<>();
        try {
            String detailUrl = "http://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?&data={%22item_num_id%22:%22" + goodsid + "%22}";
            String body = HttpUtils.doGet(detailUrl, null);
            JSONArray array = JSON.parseObject(body).getJSONObject("data").getJSONArray("images");
            for (Object o : array) {
                imgs.add((String) o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        goodsDetail.setImgs(imgs);
        return goodsDetail;
    }

    @Cacheable(value = "GoodsList", key = "#type+ '_' +#page")
    public List<Goods> findPageGoods(String type, Integer page) throws IOException {
        String url = "http://170quan.cc/index.php?r=" + type + "&page=" + page;
        return requestAndParseGoods(url);
    }

    @Cacheable(value = "GoodsList", key = "#type+ '_' + #cid + '_' + #px + '_' + #page")
    public List<Goods> findPageGoodsByCid(String type, String cid, String px, Integer page) throws IOException {
        String url = "http://170quan.cc/index.php?r=" + type + "&page=" + page + "&cid=" + cid + "&px=" + px;
        return requestAndParseGoods(url);
    }

    private List<Goods> requestAndParseGoods(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
        String body = restTemplate.postForObject(url, new HttpEntity<String>(headers), String.class);
        JSONObject data = JSON.parseObject(body);
        String content = data.getJSONObject("data").getString("content");


        List<Goods> goodsList = new ArrayList<>();
        Document document = Jsoup.parse(content);
        Iterator<Element> iterator = document.select("div.goods-item").iterator();
        while (iterator.hasNext()) {
            Goods goods = new Goods();
            Element element = iterator.next();
            String href = element.select("a.img").attr("href");
            int index = href.lastIndexOf("id=") + 3;
            int endIndex = href.length();
            int lastIndex = href.indexOf("&", index);
            if (lastIndex != -1) {
                endIndex = lastIndex;
            }
            goods.setGoodsId(href.substring(index, endIndex));
            goods.setCoupon(element.select("span.coupon-wrapper > b").text());
            goods.setImage(element.select("img.lazy").attr("data-original"));
            goods.setName(element.select("div.text").text());
            goods.setSoldNum(element.select("span.sold-num").text());
            goods.setPrice(element.select("span.price > span").text());
            goodsList.add(goods);
        }
        return goodsList;
    }

    @Override
    @Cacheable(value = "GoodsTop100", key = "'top100'")
    public List<Goods> findTop100() {
        String url = "http://api.dataoke.com/index.php?r=Port/index&type=top100&appkey=6g3nrfzgy0&v=2";
        String body = restTemplate.getForObject(url, String.class);
        JSONObject result = JSON.parseObject(body);
        JSONArray data = result.getJSONArray("result");

        List<Goods> goodsList = new ArrayList<>();
        for (Object o : data) {
            JSONObject jb = (JSONObject) o;
            Goods goods = new Goods();
            goods.setGoodsId(jb.getString("ID"));
            goods.setName(jb.getString("Title"));
            goods.setPrice(jb.getString("Price"));
            goods.setSoldNum(jb.getString("Sales_num"));
            DecimalFormat df = new DecimalFormat("#");
            goods.setCoupon(df.format(jb.getDouble("Quan_price")));
            goods.setImage(jb.getString("Pic"));
            goodsList.add(goods);
        }
        return goodsList;
    }


    @Cacheable(value = "GoodsSwipe", key = "'goods_swipe'")
    public List<Goods> findSwipeGoods() throws IOException {
        String url = "http://170quan.cc/index.php?r=index";
        Document document = Jsoup.connect(url)
                .userAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1")
                .referrer("http://170quan.cc/index.php?r=index/wap")
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8")
                .header("Accept-Encoding", "gzip, deflate")
                .header("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4")
                .header("Host", "170quan.cc")
                .header("Upgrade-Insecure-Requests", "1")
                .get();
        ListIterator<Element> elements = document.select("div.swiper-slide > a").listIterator();
        List<Goods> goodsList = new ArrayList<>();
        while (elements.hasNext()) {
            Element element = elements.next();
            Goods goods = new Goods();
            goods.setGoodsId(element.attr("data-gid"));
            goods.setImage(element.select("img").attr("src"));
            goodsList.add(goods);
        }
        return goodsList;
    }

    @Override
    public List<Goods> findGoodsSearch(String keyword, Integer page, String px) {
        String url = "http://170quan.cc/index.php?r=index/ajaxSearch&page=" + page + "&kw=" + keyword + "&px=" + px;
        List<Goods> goods = requestAndParseGoods(url);

        if (!goods.isEmpty()) {
            goodsKeywordService.updateKeyword(keyword);
        }

        return goods;
    }


    public static void main(String[] args) throws ApiException, IOException {
        TaoBaoServiceImpl taoBaoService = new TaoBaoServiceImpl();
//        TbkTpwdCreateResponse taoKouLing = taoBaoService.createTaoKouLing("台式公主镜.桌面饰品收纳梳妆镜子.模拟自然光",
//                "https://uland.taobao.com/coupon/edetail?e=OGjYoWsJJ2sGQASttHIRqZEzu5gaYtxGGNbDNMCqaspGEnS%2B6V3xGJ4%2F%2BVZDwH05HWkyfJGQxCYdxby8um6qwJQ5wfGz%2Fu%2BN1fm3aBfYuJLMBAjZVSbr62uFqp8TFaHMonv6QcvcARY%3D&traceId=0bfaca9e15154677021935354e&activityId=eba1fe2ca7874ad2a4b6fdd114b482fc",
//                "http://img.alicdn.com/imgextra/i4/3172867332/TB2hFXZXlfM8KJjSZFhXXcRyFXa_!!3172867332.jpg_400x400.jpg");
//        System.out.println(JSON.toJSONString(taoKouLing));

//        GoodsDetail goodsDetail = taoBaoService.getGoodsDetail("5121845");
//        System.out.println(JSON.toJSONString(goodsDetail));

//        taoBaoService.findPageGoods("index/ajax", 3);

//        http://170quan.cc/index.php?r=p/d&id=678242
//        http://170quan.cc/index.php?r=p/d&id=5147462&u=678242

//        String url = "http://170quan.cc/index.php?r=p/d&id=5147462&u=678242";
//        int index = url.lastIndexOf("id=") + 3;
//        int endIndex = url.length() - 1;
//        int lastIndex = url.indexOf("&", index);
//        if (lastIndex != -1) {
//            endIndex = lastIndex;
//        }
//        System.out.println(url.substring(index, endIndex));
//        taoBaoService.findTop100();

        taoBaoService.findSwipeGoods();
    }


}
